/* Copyright (C) 2014-2015 Mammoth Inc. */

/** COMPATIBILITY **/
(function() {
	if (window.attachEvent && !window.addEventListener) {
		window.location.href = "http://www.mengma.com/guide/fuckie";
	}
})();

$(function() {
	/** EMAIL SETTING **/
	/*only show unactivation tips in www.mengma.com*/
	var mm_user_name  = $('.mm_user_name').html();
	var initEmail = $('#initEmail').val();
	var dataId = $("#mm_email_setting").data("id");
	var isIndexPage = (/^http:\/\/www.mengma.com\/$/.test(window.location.href));
	var $location = window.location.href;
	if(mm_user_name!=undefined && $location=="http://www.mengma.com/"){
		if(initEmail==""){
			$(".header_email").show();
		}else{
			if (dataId == 0 && isIndexPage) {
				$(".header_email").show();
			} else if (dataId == 1) {
				$(".header_email").hide();
			}
		}
	}
	/** SCROLL **/
	if (m.not("lesson,ask")) {
		$("body").append($("<a href=\"javascript:void(0)\" id=\"mm_backtop\"><i class=\"fa fa-angle-double-up\"></i></a>"));
		$(document).scroll(function() {
			$(this).scrollTop() > $(this).height() / 4 ? $("#mm_backtop").fadeIn(300) : $("#mm_backtop").fadeOut(300);
		});
		$("#mm_backtop").click(function() {
			$("body,html").animate({
				scrollTop: 0
			}, 300);
		});
	}
	/** NOTIFY **/
	if (m.not("lesson,passport")) {
		if ($("#mm_notify_menu").length != 0) {
			M.ajax("/api/msg/getmsgnum/", {}, function(data) {
				// $("#mm_notify_num").html(data == 0 ? "" : data);
				if(data!=0){
					$("#mm_notify_badge").addClass("act");
				}else{
					$("#mm_notify_badge").removeClass("act");
				}
			});
			$("#mm_dropdown_toggle").click(function() {
				function notify_add(object, dataId, url, title, content) {
					if (content.length > 12) {
						content = content.substr(0, 12) + "...";
					}
					object.append("<a data-id=\"" + dataId + "\" class=\"mm_notify_border mm_notify_item\" href=\"" + url + "\">\
						<div class=\"row mm_notify_space\"><div class=\"col-md-2\"><i class=\"mm_notify_icon\"></i></div>\
						<div class=\"col-md-10\"><div>" + title + "</div><div>" + content + "</div></div></div></a>");
				}
				if (!$(this).hasClass("open")) {
					M.ajax("/api/msg/getmsglist/", {}, function(data) {
						if (data['SysBroadcast']) {
							$("#mm_notify_sys").html("");
							for (var j = 0; j < data['SysBroadcast'].length; j++) {
								notify_add($("#mm_notify_sys"), data['SysBroadcast'][j]['mid'], data['SysBroadcast'][j]['url'], data['SysBroadcast'][j]['title'], data['SysBroadcast'][j]['content']);
							}
						}
						if (data['QAhints']) {
							$("#mm_notify_ask").html("");
							$("#mm_notify_ask").css("max-height", "180px");
							for (var i = 0; i < data['QAhints'].length; i++) {
								notify_add($("#mm_notify_ask"), data['QAhints'][i]['mid'], data['QAhints'][i]['url'], data['QAhints'][i]['title'],decodeURIComponent(data['QAhints'][i]['content']));
							}
							if (data['QAhints'].length != $("#mm_notify_num").html()) {
								$("#mm_notify_num").html(data['QAhints'].length);
							}
							$(".mm_notify_item").click(function() {
								$that = $(this);
								M.ajax("/api/msg/tagreadmsg/", {
									mid: $(this).data("id")
								}, function(data) {
									window.location.replace($that.attr('href'));
									if (window.location.href.split('#')[0] === $that.attr('href').split('#')[0]) {
										window.location.reload();
									}
								});
							});
						}
						if(!data['SysBroadcast'] && !data['QAhints']){
							$('#mm_notify_menu').css('display','none');
						}
					});
				}
			});
		}
	}

	/** Tab Switch **/
	var isShowBlock = function(){
		var pos = 3; // 不显示滑动块
		var href = window.location.href;
		if (/^http:\/\/qa.mengma.com\/#/.test(href)) {
			pos = 2;
		} else if(/^http:\/\/oj.mengma.com\/$/.test(href)) {
			pos = 1;
		} else if(/^http:\/\/www.mengma.com\/volumes$/.test(href)) {
			pos = 0;
		}
		return pos;
	};
	var $userName = $('#userNameInput').val();
	var $userId = $('#userId').val();
	function substrUserName(){
		var maxShowLen = 7;
		if($userName){
			if($userName.length>maxShowLen){
				$userName = $userName.substr(0,6)+'...'
				$('.mm_user_name').html($userName);
			}else{
				$('.mm_user_name').html($userName);
			}
		}else{
			if($userId){
				if($userId.length==18){
					$userName = "萌小码"+ $userId.substr(8,18).substr(0,3)+'...';
				}else{
					$userName = "萌小码"+ $userId.substr(0,3)+'...';
				}
				$('.mm_user_name').html($userName);
			}
		}
	}
	substrUserName();
	var initBlock = function(){
		if(!$(".mm_navbar_active").length) {
			$('.mm_navbar_nav').append('<div class="mm_navbar_active"></div>');
		}
		return $(".mm_navbar_active");
	};

	//fix bug about white color font
	var changeColor = function(index) {
       $(".mm_navbar_nav .navbar_slide_li").each(function(index){
			$(this).find('a').removeClass("mm_navbar_nav_active");
			$(this).find('img').attr('src','http://s.mengma.com/img/mm_gray_'+index+'.svg');
       });
       $(".mm_navbar_nav a").eq(index).addClass("mm_navbar_nav_active");
       $('.mm_navbar_nav_active').find('img').attr('src','http://s.mengma.com/img/mm_white_'+index+'.svg');

    }

    var slideBlock = function(block, width, pos, moveTime){
    	block.stop().animate({
			left: width * pos + "",
			width: width + ""
		}, moveTime, changeColor(pos));
    };

    var currentPageIndex = isShowBlock();
	if(currentPageIndex < 3) { // 3个项目首页滑动效果
		var block = initBlock();
		var navbarLiWidth = $(".navbar_slide_li").eq(0).width();
		//init
		slideBlock(block, navbarLiWidth, currentPageIndex, 300);
		//slide
		$(".navbar_slide_li").find("a").mouseenter(function(e) {
			e.stopPropagation();
			slideBlock(block, navbarLiWidth, $(this).closest("a").data("type"), 300);
		});
		//mouseleave
		$(document).on("mouseleave", ".mm_navbar_nav", function(){
			slideBlock(block, navbarLiWidth, currentPageIndex, 300);
		});
	} else {//鼠标划入时候滑动 划出消失
		$(".navbar_slide_li").find("a").hover(function() {
			var navbarLiWidth = $(".navbar_slide_li").eq(0).width();
			slideBlock(initBlock(), navbarLiWidth, $(this).closest("a").data("type"), 300);
		});
		$(document).on("mouseleave", ".mm_navbar_nav", function(){
			$(".mm_navbar_active").remove();
			$(".mm_navbar_nav .navbar_slide_li").each(function(index){
				$(this).find('img').attr('src','http://s.mengma.com/img/mm_gray_'+index+'.svg');
				$(this).find('a').removeClass("mm_navbar_nav_active");
       		});
		});
	}
	/** continue url **/
	var needContinue = function(){
		var isNeededContinue = false; 
		var href = window.location.href;
		isNeededContinue = /^http:\/\/qa.mengma.com\/$/.test(href) ||
							/^http:\/\/oj.mengma.com\/$/.test(href) ||
							/^http:\/\/www.mengma.com\/volumes$/.test(href) ||
							/^http:\/\/www.mengma.com\/$/.test(href);
		if(isNeededContinue && /登录/.test($(".navbar-nav a").last().html())){
			$(".navbar-nav a").last().attr("href", "http://passport.mengma.com?continue=" + window.location.href);
		}
	}
	needContinue();

	/** SCROLL **/
	if (m.not("lesson,ask")) {
		$("body").append($("<a href=\"javascript:void(0)\" id=\"mm_backtop\"><i class=\"fa fa-angle-double-up\"></i></a>"));
		$(document).scroll(function() {
			$(this).scrollTop() > $(this).height() / 4 ? $("#mm_backtop").fadeIn(300) : $("#mm_backtop").fadeOut(300);
		});
		$("#mm_backtop").click(function() {
			$("body,html").animate({
				scrollTop: 0
			}, 300);
		});
	}
	
	/** HIRE **/
	if (typeof window.console === "object") {
		console.log("%c                    QM  ,\n                 ;H,MM9MM\n                  .MMMMM#\n                  :MMMMMMMM9.\n                ;MMMMMMMMMMMM#\n     r9B#MM&s. sMMMMA;''':XMMMMM\n  :MMMMMMMMMMMMMM#M:        3MMMM\n AMMMMr''''sMMMM#M5          MMMM\nhMMMM;       9MMMM           MMMM\nMM#M          MMMM           MMMM\nMMM#          MMMM           MMMM\nMMMM          MMMM           MMMM\nMMMM          MMMM          3MMMi\nMMMM          MMMM        ;MMMMi\nMMMM          MMMM      sMMMMh\nMMMM          MMMM      MMS,", "color:#31566c");
		console.log("%c欢迎加入萌萌哒的萌码团队 >3< 和我们一起改变世界！", "color:#e89640");
		console.log("%c请发送简历至 %cjob@mengma.com%c 并告诉我们你的梦想！", "color:#00c15a", "color:#11364c", "color:#00c15a");
	}
	
});

/** WXSHARING **/
var WXJSBConf = {
	'img_url': "http://s.mengma.com/img/mm_icon.png",
	'link': window.location.href,
	'url': window.location.href,
	'content': $("meta[name='description']").attr("content"),
	"desc": $("meta[name='description']").attr("content"),
	'title': document.title,
	'appid': "wxb6e377307cc6f6bc"
};
document.addEventListener("WeixinJSBridgeReady", function onBridgeReady() {
	WeixinJSBridge.on("menu:share:appmessage", function(argv) {
		WeixinJSBridge.invoke("sendAppMessage", WXJSBConf, function(res) {
			_report("send_msg", res.err_msg);
		});
	});
	WeixinJSBridge.on("menu:share:timeline", function(argv) {
		WeixinJSBridge.invoke("shareTimeline", WXJSBConf, function(res) {
			_report("timeline", res.err_msg);
		});
	});
	WeixinJSBridge.on("menu:share:weibo", function(argv) {
		WeixinJSBridge.invoke("shareWeibo", WXJSBConf, function(res) {
			_report("weibo", res.err_msg);
		});
	});
}, false);

/** NPROGRESS **/
$(document).ready(function() {
	NProgress.start();

});
$(window).load(function() {
	NProgress.done();
});
$(document).ajaxStart(function() {
	NProgress.start();
});
$(document).ajaxStop(function() {
	NProgress.done();
});

/** BAIDU ANALYZATION **/
var _hmt = _hmt || [];
_hmt.push(['_setAccount', 'edc015a9764f7919fe78a524ef9d3cb1']);

(function() {
  var hm = document.createElement("script");
  hm.src = "//hm.baidu.com/hm.js?edc015a9764f7919fe78a524ef9d3cb1";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();

var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://");
document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3Fedc015a9764f7919fe78a524ef9d3cb1' type='text/javascript'%3E%3C/script%3E"));

if(!(navigator.userAgent.indexOf('Mac OS X') > 0)) {
	$("html").niceScroll({
		styler:"fb", 
		cursorwidth:"8px",
		cursorcolor:"#7a7777",
		cursorborder:"",
		horizrailenabled: false,
		zindex:99
	});
	$("textarea").niceScroll({
		styler:"fb", 
		cursorwidth:"8px",
		cursorcolor:"#7a7777",
		cursorborder:"",
		horizrailenabled: false
	});
}

/**  Phenix  **/
var popup = function(data,callback) {
	Phenix.init({
		width: 500,
		height: 300,
		template: "<div style=\"color:{{color}};\" class=\"mm_temp_face\">{{face}}</div><div class=\"mm_temp_title\">{{title}}</div>",
		data: data
	}).show(function() {
		if(callback == null) {
			setTimeout(function() {Phenix.hide();},3000);
		} else {
			callback();
		}
	});
}

function IsLoginCookie(){
	if(document.cookie.indexOf("MMUSS=")!="-1"){
	M.cookie.clear("unlogin","domain",".mengma.com");
	} else{
		document.cookie = "unlogin=" + M.crypto.md5(Date.parse(new Date()).toString() + parseInt(100*Math.random())) + ";domain=.mengma.com;path=/";
	}
}

IsLoginCookie();

